<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智慧医院资源调度系统 - 仪表盘</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .card {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            border: 1px solid rgba(0, 0, 0, 0.125);
        }
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .stat-card .card-body {
            padding: 1.5rem;
        }
        .stat-number {
            font-size: 2.5rem;
            font-weight: bold;
        }
        .chart-container {
            position: relative;
            height: 300px;
        }
        .navbar-brand {
            font-weight: bold;
        }
        .sidebar {
            min-height: 100vh;
            background-color: #f8f9fa;
        }
        .sidebar .nav-link {
            color: #495057;
            padding: 0.75rem 1rem;
        }
        .sidebar .nav-link:hover {
            background-color: #e9ecef;
        }
        .sidebar .nav-link.active {
            background-color: #007bff;
            color: white;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav class="col-md-3 col-lg-2 d-md-block sidebar collapse">
                <div class="position-sticky pt-3">
                    <div class="text-center mb-4">
                        <h4 class="text-primary">智慧医院调度系统</h4>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link active" href="/dashboard">
                                <i class="fas fa-tachometer-alt me-2"></i>仪表盘
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/appointments">
                                <i class="fas fa-calendar-alt me-2"></i>预约管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/resources">
                                <i class="fas fa-hospital me-2"></i>资源管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/scheduling">
                                <i class="fas fa-cogs me-2"></i>调度管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="/analytics">
                                <i class="fas fa-chart-line me-2"></i>数据分析
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主内容区 -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">仪表盘</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <div class="btn-group me-2">
                            <button type="button" class="btn btn-sm btn-outline-secondary">导出报告</button>
                        </div>
                        <button type="button" class="btn btn-sm btn-primary" onclick="refreshDashboard()">
                            <i class="fas fa-sync-alt me-1"></i>刷新
                        </button>
                    </div>
                </div>

                <!-- 统计卡片 -->
                <div class="row mb-4">
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card stat-card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <div class="stat-number" id="total-appointments">-</div>
                                        <div>总预约数</div>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-calendar-alt fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card stat-card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <div class="stat-number" id="today-appointments">-</div>
                                        <div>今日预约</div>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-calendar-day fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card stat-card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <div class="stat-number" id="resource-utilization">-</div>
                                        <div>资源利用率(%)</div>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-chart-pie fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-xl-3 col-md-6 mb-4">
                        <div class="card stat-card">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <div class="stat-number" id="avg-wait-time">-</div>
                                        <div>平均等待时间(分钟)</div>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-clock fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 图表区域 -->
                <div class="row">
                    <div class="col-lg-8 mb-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">预约趋势</h5>
                            </div>
                            <div class="card-body">
                                <div class="chart-container">
                                    <canvas id="appointmentChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-4 mb-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">资源分布</h5>
                            </div>
                            <div class="card-body">
                                <div class="chart-container">
                                    <canvas id="resourceChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-lg-12 mb-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">资源利用率趋势</h5>
                            </div>
                            <div class="card-body">
                                <div class="chart-container">
                                    <canvas id="utilizationChart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 最近调度结果 -->
                <div class="row">
                    <div class="col-lg-12">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">最近调度结果</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-striped">
                                        <thead>
                                            <tr>
                                                <th>调度ID</th>
                                                <th>算法</th>
                                                <th>资源利用率</th>
                                                <th>等待时间</th>
                                                <th>公平性评分</th>
                                                <th>创建时间</th>
                                            </tr>
                                        </thead>
                                        <tbody id="recent-schedules">
                                            <!-- 动态加载数据 -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
    <script>
        // 全局变量
        let appointmentChart, resourceChart, utilizationChart;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadDashboardData();
            loadChartData();
        });

        // 加载仪表盘数据
        async function loadDashboardData() {
            try {
                const response = await fetch('/api/dashboard/stats', {
                    headers: {
                        'Authorization': 'Bearer ' + getToken()
                    }
                });
                const data = await response.json();
                
                if (response.ok) {
                    updateStats(data);
                    updateRecentSchedules(data.recent_schedules);
                } else {
                    console.error('加载数据失败:', data.error);
                }
            } catch (error) {
                console.error('请求失败:', error);
            }
        }

        // 加载图表数据
        async function loadChartData() {
            try {
                const response = await fetch('/api/dashboard/charts', {
                    headers: {
                        'Authorization': 'Bearer ' + getToken()
                    }
                });
                const data = await response.json();
                
                if (response.ok) {
                    createCharts(data);
                } else {
                    console.error('加载图表数据失败:', data.error);
                }
            } catch (error) {
                console.error('请求失败:', error);
            }
        }

        // 更新统计数据
        function updateStats(data) {
            document.getElementById('total-appointments').textContent = data.appointments.total;
            document.getElementById('today-appointments').textContent = data.appointments.today;
            document.getElementById('resource-utilization').textContent = data.performance.resource_utilization;
            document.getElementById('avg-wait-time').textContent = data.performance.avg_wait_time;
        }

        // 更新最近调度结果
        function updateRecentSchedules(schedules) {
            const tbody = document.getElementById('recent-schedules');
            tbody.innerHTML = '';
            
            schedules.forEach(schedule => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${schedule.id}</td>
                    <td><span class="badge bg-primary">${schedule.algorithm}</span></td>
                    <td>${schedule.utilization.toFixed(2)}%</td>
                    <td>${schedule.wait_time.toFixed(1)}分钟</td>
                    <td>${schedule.fairness.toFixed(2)}</td>
                    <td>${new Date(schedule.created_at).toLocaleString()}</td>
                `;
                tbody.appendChild(row);
            });
        }

        // 创建图表
        function createCharts(data) {
            // 预约趋势图
            const appointmentCtx = document.getElementById('appointmentChart').getContext('2d');
            appointmentChart = new Chart(appointmentCtx, {
                type: 'line',
                data: {
                    labels: data.appointment_trend.map(item => item.date),
                    datasets: [{
                        label: '预约数量',
                        data: data.appointment_trend.map(item => item.count),
                        borderColor: 'rgb(75, 192, 192)',
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        tension: 0.1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });

            // 资源分布图
            const resourceCtx = document.getElementById('resourceChart').getContext('2d');
            resourceChart = new Chart(resourceCtx, {
                type: 'doughnut',
                data: {
                    labels: data.resource_distribution.map(item => item.type),
                    datasets: [{
                        data: data.resource_distribution.map(item => item.count),
                        backgroundColor: [
                            '#FF6384',
                            '#36A2EB',
                            '#FFCE56',
                            '#4BC0C0',
                            '#9966FF'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });

            // 资源利用率趋势图
            const utilizationCtx = document.getElementById('utilizationChart').getContext('2d');
            utilizationChart = new Chart(utilizationCtx, {
                type: 'bar',
                data: {
                    labels: data.utilization_trend.map(item => item.date),
                    datasets: [{
                        label: '资源利用率(%)',
                        data: data.utilization_trend.map(item => item.utilization),
                        backgroundColor: 'rgba(54, 162, 235, 0.8)',
                        borderColor: 'rgba(54, 162, 235, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100
                        }
                    }
                }
            });
        }

        // 刷新仪表盘
        function refreshDashboard() {
            loadDashboardData();
            loadChartData();
        }

        // 获取JWT令牌
        function getToken() {
            return localStorage.getItem('token') || '';
        }

        // 自动刷新（每5分钟）
        setInterval(refreshDashboard, 300000);
    </script>
</body>
</html>
